package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 */

public abstract class CookieUtil {
    /**
     * 往浏览器里添加token
     * @param token
     * @param response
     */
    public static void setCookie(String token, HttpServletResponse response) {
        Cookie cookie = new Cookie("token",token);
        //cookie存活时间,要转为int类型
        cookie.setMaxAge(RedisKeys.USER_TOKEN.getTime().intValue());
        //cookie的共享路径,要记得配这个!!
        cookie.setPath("/");
        //共享存入到浏览器中
        response.addCookie(cookie);
    }

    /**
     * 返回token
     * @param request
     * @param response
     * @return
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    //延长cookie的时间
                    token = cookie.getValue();
                    CookieUtil.setCookie(token, response);
                    return token;
                }
            }
        }
        return null;
    }

    public static void removeCookie(Cookie cookie,HttpServletResponse response){
        cookie.setMaxAge(0);
        cookie.setPath("/"); //路径一定要写上，不然干不掉的
        response.addCookie(cookie);
    }

}
